{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Uncertainty calculation for model: HM1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import the libraries\n",
    "import ee\n",
    "import pandas as pd\n",
    "import os\n",
    "import numpy as np\n",
    "import random\n",
    "from random import sample\n",
    "import itertools \n",
    "import geopandas as gpd\n",
    "from sklearn.metrics import r2_score\n",
    "from termcolor import colored # this is allocate colour and fonts type for the print title and text\n",
    "from IPython.display import display, HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#set the working directory of local drive for Grid search result table loading\n",
    "# os.getcwd()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# initialize the earth engine API\n",
    "ee.Initialize()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1 Load the required composites, images and settings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "#definet the color pallette\n",
    "vibgYOR = ['330044', '220066', '1133cc', '33dd00', 'ffda21', 'ff6622', 'd10000']\n",
    "compositeImage =ee.Image(\"users/leonidmoore/ForestBiomass/20200915_Forest_Biomass_Predictors_Image\")\n",
    "compositeImageNew = ee.Image(\"projects/crowtherlab/Composite/CrowtherLab_Composite_30ArcSec\");\n",
    "unboundedGeo = ee.Geometry.Polygon([-180, 88, 0, 88, 180, 88, 180, -88, 0, -88, -180, -88], None, False)\n",
    "# generete the pixel area map\n",
    "pixelArea = ee.Image.pixelArea().divide(10000) # to ha unit\n",
    "# load the biome layer\n",
    "biomeLayer = compositeImage.select(\"WWF_Biome\")\n",
    "biomeMask = biomeLayer.mask(biomeLayer.neq(98)).mask(biomeLayer.neq(99)).gt(0)\n",
    "# load the mean maps for present and potential\n",
    "# load the carbon concentration map\n",
    "carbonConcentration = ee.Image(\"users/leonidmoore/ForestBiomass/Biome_level_Wood_Carbon_Conentration_Map\")\n",
    "# load the biomass density layers\n",
    "mergedAGB_PresentMean =  ee.Image(\"users/leonidmoore/ForestBiomass/SpawnMap/Spawn_Harmonized_AGB_density_Map_1km\").select('agb').unmask() \n",
    "mergedAGB_PotentialMean = ee.Image(\"users/leonidmoore/ForestBiomass/GroundSourcedModel/EnsambledMaps/Predicted_HM1_Potential_density_Ensambled_Mean\").unmask()\n",
    "# define the standardized projection\n",
    "stdProj = mergedAGB_PresentMean.projection()\n",
    "# load the two forest cover layer for existing and potential forest\n",
    "presentForestCover = compositeImage.select('PresentTreeCover').unmask()# make sure it's in  0-1 scale\n",
    "potentialForestCover = ee.Image(\"users/leonidmoore/ForestBiomass/Bastin_et_al_2019_Potential_Forest_Cover_Adjusted\").unmask() # make sure it's in  0-1 scale\n",
    "\n",
    "# define the present and potential forest cover masks\n",
    "presentMask = presentForestCover.gt(0)\n",
    "potentialMask = potentialForestCover.gt(0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2 Calculate the present and potential AGB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# check the difference of the two density maps\n",
    "potentialHigher = mergedAGB_PotentialMean.multiply(pixelArea).subtract(mergedAGB_PresentMean.multiply(pixelArea)).gte(0)\n",
    "potentialLower = mergedAGB_PotentialMean.multiply(pixelArea).subtract(mergedAGB_PresentMean.multiply(pixelArea)).lt(0)\n",
    "# replace the lower potential value by present biomass density value\n",
    "potentialAGB_Density = mergedAGB_PresentMean.multiply(potentialLower).add(mergedAGB_PotentialMean.multiply(potentialHigher))\n",
    "presentAGB_Density = mergedAGB_PresentMean\n",
    "# get the abs of present and potential AGB\n",
    "presentAGB_Abs = presentAGB_Density.multiply(pixelArea).multiply(presentMask).divide(1000000000)\n",
    "potentialAGB_Abs = potentialAGB_Density.multiply(pixelArea).multiply(potentialMask).divide(1000000000)\n",
    "\n",
    "# presentAGB_Abs_Sum = presentAGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                  geometry = unboundedGeo,\n",
    "#                                                  crs = 'EPSG:4326',\n",
    "#                                                  crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                  maxPixels = 1e9)\n",
    "# # print the estimation out\n",
    "# print(colored('The present AGB:', 'blue', attrs=['bold']),presentAGB_Abs_Sum.getInfo())\n",
    "# potentialAGB_Abs_Sum = potentialAGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                      geometry = unboundedGeo,\n",
    "#                                                      crs = 'EPSG:4326',\n",
    "#                                                      crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                      maxPixels = 1e9)\n",
    "# # print the estimation out\n",
    "# print(colored('The potential AGB:', 'blue', attrs=['bold']),potentialAGB_Abs_Sum.getInfo())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3 Calculate the Upper and Lower of present and potential AGB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the present prediction lower and upper layer\n",
    "mergedPredictionInterval = ee.Image(\"users/leonidmoore/ForestBiomass/SpawnMap/Spawn_Harmonized_AGB_density_Map_1km\").select('err').unmask()\n",
    "presentAGB_Lower1 = mergedAGB_PresentMean.subtract(mergedPredictionInterval)\n",
    "presentAGB_Lower = presentAGB_Lower1.mask(presentAGB_Lower1.gte(0)).unmask()\n",
    "presentAGB_Upper = mergedAGB_PresentMean.add(mergedPredictionInterval)\n",
    "\n",
    "# get the upper and lower layer\n",
    "mergedAGB_PotentialLower = ee.Image(\"users/leonidmoore/ForestBiomass/GroundSourcedModel/EnsambledMaps/Predicted_HM1_Potential_density_Ensambled_Percentile\").select(['lower']).unmask() \n",
    "mergedAGB_PotentialUpper = ee.Image(\"users/leonidmoore/ForestBiomass/GroundSourcedModel/EnsambledMaps/Predicted_HM1_Potential_density_Ensambled_Percentile\").select(['upper']).unmask() \n",
    "\n",
    "mergedAGB_PotentialLower1 = presentAGB_Lower.multiply(potentialLower).add(mergedAGB_PotentialLower.multiply(potentialHigher))\n",
    "mergedAGB_PotentialUpper1 = presentAGB_Upper.multiply(potentialLower).add(mergedAGB_PotentialUpper.multiply(potentialHigher))\n",
    "\n",
    "# define the masks to mask the present and potential lower maps\n",
    "potentialAGB_Lower_Larger = mergedAGB_PotentialLower1.subtract(presentAGB_Lower).gte(0) # potential is larger than present mean\n",
    "potentialAGB_Lower_Smaller = mergedAGB_PotentialLower1.subtract(presentAGB_Lower).lt(0)\n",
    "# define the masks to mask the present and potential upper maps\n",
    "potentialAGB_Upper_Larger = mergedAGB_PotentialUpper1.subtract(presentAGB_Upper).gte(0) # potential is larger than present upper\n",
    "potentialAGB_Upper_Smaller = mergedAGB_PotentialUpper1.subtract(presentAGB_Upper).lt(0)\n",
    "\n",
    "# replace the lower potential value by present biomass density value\n",
    "potentialAGB_AdjLower = mergedAGB_PotentialLower.multiply(potentialAGB_Lower_Larger).add(presentAGB_Lower.multiply(potentialAGB_Lower_Smaller))\n",
    "potentialAGB_AdjUpper = mergedAGB_PotentialUpper.multiply(potentialAGB_Upper_Larger).add(presentAGB_Upper.multiply(potentialAGB_Upper_Smaller))\n",
    "\n",
    "# present lower and higher\n",
    "presentAGB_Lower_Abs = presentAGB_Lower.multiply(pixelArea).multiply(presentMask).divide(1000000000)\n",
    "presentAGB_Upper_Abs = presentAGB_Upper.multiply(pixelArea).multiply(presentMask).divide(1000000000)\n",
    "\n",
    "# abs potential lower and higher\n",
    "potentialAGB_Lower_Abs = potentialAGB_AdjLower.multiply(pixelArea).multiply(potentialMask).divide(1000000000)\n",
    "potentialAGB_Upper_Abs = potentialAGB_AdjUpper.multiply(pixelArea).multiply(potentialMask).divide(1000000000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Calculate the present AGB lower\n",
    "# presentAGB_Lower_Sum = presentAGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                          geometry = unboundedGeo,\n",
    "#                                                          crs = 'EPSG:4326',\n",
    "#                                                          crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                          maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present AGB Lower:', 'blue', attrs=['bold']),presentAGB_Lower_Sum.getInfo())\n",
    "\n",
    "# # Calculate the present AGB upper\n",
    "# presentAGB_Upper_Sum = presentAGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                          geometry = unboundedGeo,\n",
    "#                                                          crs = 'EPSG:4326',\n",
    "#                                                          crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                          maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present AGB Upper:', 'blue', attrs=['bold']),presentAGB_Upper_Sum.getInfo())\n",
    "\n",
    "# potentialAGB_Lower_Sum = potentialAGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                              geometry = unboundedGeo,\n",
    "#                                                              crs = 'EPSG:4326',\n",
    "#                                                              crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                              maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential AGB Lower:', 'blue', attrs=['bold']),potentialAGB_Lower_Sum.getInfo())\n",
    "\n",
    "# potentialAGB_Upper_Sum = potentialAGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                              geometry = unboundedGeo,\n",
    "#                                                              crs = 'EPSG:4326',\n",
    "#                                                              crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                              maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential AGB Upper:', 'blue', attrs=['bold']),potentialAGB_Upper_Sum.getInfo())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4 Calculate the Upper and Lower of present and potential Root and TGB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the root shoot map\n",
    "rootShootRatio = ee.Image(\"users/leonidmoore/ForestBiomass/Root_shoot_ratio_Map\").unmask()\n",
    "rootShootRatioLower = ee.Image(\"users/leonidmoore/ForestBiomass/Root_shoot_ratio_percentile_Map\").select('lower').unmask()\n",
    "rootShootRatioUpper = ee.Image(\"users/leonidmoore/ForestBiomass/Root_shoot_ratio_percentile_Map\").select('upper').unmask()\n",
    "# \n",
    "presentRoot_Lower_Abs = presentAGB_Lower_Abs.multiply(rootShootRatioLower).mask(presentMask)\n",
    "presentRoot_Upper_Abs = presentAGB_Upper_Abs.multiply(rootShootRatioUpper).mask(presentMask)\n",
    "\n",
    "potentialRoot_Lower_Abs = potentialAGB_Lower_Abs.multiply(rootShootRatioLower).mask(potentialMask)\n",
    "potentialRoot_Upper_Abs = potentialAGB_Upper_Abs.multiply(rootShootRatioUpper).mask(potentialMask)\n",
    "\n",
    "presentRoot_Abs = presentAGB_Abs.multiply(rootShootRatio).mask(presentMask)\n",
    "potentialRoot_Abs = potentialAGB_Abs.multiply(rootShootRatio).mask(potentialMask)\n",
    "\n",
    "presentTGB_Abs = presentAGB_Abs.multiply(rootShootRatio).add(presentAGB_Abs)#.multiply(presentMask)\n",
    "potentialTGB_Abs = potentialAGB_Abs.multiply(rootShootRatio).add(potentialAGB_Abs)#.multiply(potentialMask)\n",
    "\n",
    "presentTGB  = presentAGB_Density.multiply(rootShootRatio.add(1))\n",
    "# density \n",
    "presentRoot = presentAGB_Density.multiply(rootShootRatio)\n",
    "presentRoot_Lower = presentAGB_Lower.multiply(rootShootRatioLower)\n",
    "presentRoot_Upper = presentAGB_Upper.multiply(rootShootRatioLower)\n",
    "\n",
    "potentialRoot_Lower = potentialAGB_AdjLower.multiply(rootShootRatioLower)\n",
    "potentialRoot_Upper = potentialAGB_AdjUpper.multiply(rootShootRatioLower)\n",
    "\n",
    "presentTGB_Lower = presentAGB_Lower.multiply(rootShootRatioLower).add(presentAGB_Lower)\n",
    "presentTGB_Upper = presentAGB_Upper.multiply(rootShootRatioLower).add(presentAGB_Upper)\n",
    "\n",
    "potentialTGB_Lower = potentialAGB_AdjLower.multiply(rootShootRatioLower).add(potentialAGB_AdjLower)\n",
    "potentialTGB_Upper = potentialAGB_AdjUpper.multiply(rootShootRatioLower).add(potentialAGB_AdjUpper)\n",
    "\n",
    "# presentTGB_Abs_Sum = presentTGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                  geometry = unboundedGeo,\n",
    "#                                                  crs = 'EPSG:4326',\n",
    "#                                                  crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                  maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present TGB:', 'blue', attrs=['bold']),presentTGB_Abs_Sum.getInfo())\n",
    "\n",
    "# potentialTGB_Abs_Sum = potentialTGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                      geometry = unboundedGeo,\n",
    "#                                                      crs = 'EPSG:4326',\n",
    "#                                                      crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                      maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential TGB:', 'blue', attrs=['bold']),potentialTGB_Abs_Sum.getInfo())\n",
    "\n",
    "# presentRoot_Abs_Sum = presentRoot_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                    geometry = unboundedGeo,\n",
    "#                                                    crs = 'EPSG:4326',\n",
    "#                                                    crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                    maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Roots:', 'blue', attrs=['bold']),presentRoot_Abs_Sum.getInfo())\n",
    "\n",
    "# potentialRoot_Abs_Sum = potentialRoot_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Roots:', 'blue', attrs=['bold']),potentialRoot_Abs_Sum.getInfo())\n",
    "\n",
    "# presentRoot_Lower_Sum = presentRoot_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Roots Lower:', 'blue', attrs=['bold']),presentRoot_Lower_Sum.getInfo())\n",
    "\n",
    "# presentRoot_Upper_Sum = presentRoot_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Roots Upper:', 'blue', attrs=['bold']),presentRoot_Upper_Sum.getInfo())\n",
    "\n",
    "# potentialRoot_Lower_Sum = potentialRoot_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Roots Lower:', 'blue', attrs=['bold']),potentialRoot_Lower_Sum.getInfo())\n",
    "# potentialRoot_Upper_Sum = potentialRoot_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Roots Upper:', 'blue', attrs=['bold']),potentialRoot_Upper_Sum.getInfo())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "presentTGB_Lower_Abs = presentAGB_Lower_Abs.multiply(rootShootRatioLower.add(1))\n",
    "presentTGB_Upper_Abs = presentAGB_Upper_Abs.multiply(rootShootRatioUpper.add(1))\n",
    "\n",
    "potentialTGB_Lower_Abs = potentialAGB_Lower_Abs.multiply(rootShootRatioLower.add(1))\n",
    "potentialTGB_Upper_Abs = potentialAGB_Upper_Abs.multiply(rootShootRatioUpper.add(1))\n",
    "\n",
    "# presentTGB_Lower_Sum = presentTGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present TGB Lower:', 'blue', attrs=['bold']),presentTGB_Lower_Sum.getInfo())\n",
    "\n",
    "# presentTGB_Upper_Sum = presentTGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present TGB Upper:', 'blue', attrs=['bold']),presentTGB_Upper_Sum.getInfo())\n",
    "\n",
    "# potentialTGB_Lower_Sum = potentialTGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential TGB Lower:', 'blue', attrs=['bold']),potentialTGB_Lower_Sum.getInfo())\n",
    "# potentialTGB_Upper_Sum = potentialTGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential TGB Upper:', 'blue', attrs=['bold']),potentialTGB_Upper_Sum.getInfo())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5 Calculate the Upper and Lower of present and potential Root and PGB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the dead wood and litter layer\n",
    "deadWoodLitterRatio = ee.Image(\"users/leonidmoore/ForestBiomass/DeadWoodLitter/DeadWood_Litter_Ratio_Map\").unmask()\n",
    "deadWoodLitterRatioLower = ee.Image(\"users/leonidmoore/ForestBiomass/DeadWoodLitter/DeadWood_Litter_Ratio_Lower_Map\").unmask()\n",
    "deadWoodLitterRatioUpper = ee.Image(\"users/leonidmoore/ForestBiomass/DeadWoodLitter/DeadWood_Litter_Ratio_Upper_Map\").unmask()\n",
    "\n",
    "# calculate the present and potential PGB\n",
    "presentPGB_Abs = presentTGB_Abs.multiply(deadWoodLitterRatio)\n",
    "potentialPGB_Abs = potentialTGB_Abs.multiply(deadWoodLitterRatio)\n",
    "\n",
    "# calculate the present and potential dead wood and litter\n",
    "presentLitter_Abs = presentTGB_Abs.multiply(deadWoodLitterRatio.subtract(1))\n",
    "potentialLitter_Abs = potentialTGB_Abs.multiply(deadWoodLitterRatio.subtract(1))\n",
    "\n",
    "# calculate the present Dead wood and litter\n",
    "presentLitter_Lower_Abs = presentTGB_Lower_Abs.multiply(deadWoodLitterRatioLower.subtract(1))\n",
    "presentLitter_Upper_Abs = presentTGB_Upper_Abs.multiply(deadWoodLitterRatioUpper.subtract(1))\n",
    "# calculate the potential dead wood and litter\n",
    "potentialLitter_Lower_Abs = potentialTGB_Lower_Abs.multiply(deadWoodLitterRatioLower.subtract(1))\n",
    "potentialLitter_Upper_Abs = potentialTGB_Upper_Abs.multiply(deadWoodLitterRatioUpper.subtract(1))\n",
    "# get the densities\n",
    "presentPGB_Lower = presentTGB_Lower.multiply(deadWoodLitterRatioLower)\n",
    "presentPGB_Upper = presentTGB_Upper.multiply(deadWoodLitterRatioUpper)\n",
    "\n",
    "potentialPGB_Lower = potentialTGB_Lower.multiply(deadWoodLitterRatioLower)\n",
    "potentialPGB_Lower = potentialTGB_Lower.multiply(deadWoodLitterRatioUpper)\n",
    "\n",
    "presentLitter_Lower = presentTGB_Lower.multiply(deadWoodLitterRatioLower.subtract(1))\n",
    "presentLitter_Upper = presentTGB_Upper.multiply(deadWoodLitterRatioUpper.subtract(1))\n",
    "\n",
    "potentialLitter_Lower = potentialTGB_Lower.multiply(deadWoodLitterRatioLower.subtract(1))\n",
    "potentialLitter_Lower = potentialTGB_Lower.multiply(deadWoodLitterRatioUpper.subtract(1))\n",
    "\n",
    "# presentPGB_Abs_Sum = presentPGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present PGB:', 'blue', attrs=['bold']),presentPGB_Abs_Sum.getInfo())\n",
    "\n",
    "# potentialPGB_Abs_Sum = potentialPGB_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential PGB:', 'blue', attrs=['bold']),potentialPGB_Abs_Sum.getInfo())\n",
    "\n",
    "# presentLitter_Abs_Sum = presentLitter_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Dead wood and litter:', 'blue', attrs=['bold']),presentLitter_Abs_Sum.getInfo())\n",
    "\n",
    "# potentialLitter_Abs_Sum = potentialLitter_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Dead wood and litter:', 'blue', attrs=['bold']),potentialLitter_Abs_Sum.getInfo())\n",
    "\n",
    "# presentLitter_Lower_Sum = presentLitter_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Dead wood and litter Lower:', 'blue', attrs=['bold']),presentLitter_Lower_Sum.getInfo())\n",
    "\n",
    "# presentLitter_Upper_Sum = presentLitter_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present Dead wood and litter Upper:', 'blue', attrs=['bold']),presentLitter_Upper_Sum.getInfo())\n",
    "\n",
    "# potentialLitter_Lower_Sum = potentialLitter_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Dead wood and litter Lower:', 'blue', attrs=['bold']),potentialLitter_Lower_Sum.getInfo())\n",
    "\n",
    "# potentialLitter_Upper_Sum = potentialLitter_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "# # print the estimation out\n",
    "# print(colored('The potential Dead wood and litter Upper:', 'blue', attrs=['bold']),potentialLitter_Upper_Sum.getInfo())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "# calculate the present PGB Lower and Upper\n",
    "presentPGB_Lower_Abs = presentTGB_Lower_Abs.multiply(deadWoodLitterRatioLower)\n",
    "presentPGB_Upper_Abs = presentTGB_Upper_Abs.multiply(deadWoodLitterRatioUpper)\n",
    "# calculate the potential PGB Lower and Upper\n",
    "potentialPGB_Lower_Abs = potentialTGB_Lower_Abs.multiply(deadWoodLitterRatioLower)\n",
    "potentialPGB_Upper_Abs = potentialTGB_Upper_Abs.multiply(deadWoodLitterRatioUpper)\n",
    "\n",
    "presentPGB_D = presentAGB_Density.multiply(rootShootRatio.add(1)).multiply(deadWoodLitterRatio)\n",
    "potentialPGB_D = potentialAGB_Density.multiply(rootShootRatio.add(1)).multiply(deadWoodLitterRatio)\n",
    "\n",
    "# presentPGB_Lower_Sum = presentPGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present PGB Lower:', 'blue', attrs=['bold']),presentPGB_Lower_Sum.getInfo())\n",
    "\n",
    "# presentPGB_Upper_Sum = presentPGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The present PGB Upper:', 'blue', attrs=['bold']),presentPGB_Upper_Sum.getInfo())\n",
    "\n",
    "# potentialPGB_Lower_Sum = potentialPGB_Lower_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential PGB Lower:', 'blue', attrs=['bold']),potentialPGB_Lower_Sum.getInfo())\n",
    "\n",
    "# potentialPGB_Upper_Sum = potentialPGB_Upper_Abs.multiply(biomeMask).reduceRegion(reducer = ee.Reducer.sum(),\n",
    "#                                                        geometry = unboundedGeo,\n",
    "#                                                        crs = 'EPSG:4326',\n",
    "#                                                        crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "#                                                        maxPixels = 1e9)\n",
    "\n",
    "# # print the estimation out\n",
    "# print(colored('The potential PGB Upper:', 'blue', attrs=['bold']),potentialPGB_Upper_Sum.getInfo())\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6 Export the upper and lower images to Assets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load the carbon density layers\n",
    "SandermannCarbonDiff = ee.Image(\"users/leonidmoore/ForestBiomass/SoilOrganicCarbonModel/SOCS_0_200cm_Diff_1km_Present_subtract_NoLU\").unmask()\n",
    "SandermannCarbonPresent = ee.Image(\"users/leonidmoore/ForestBiomass/SoilOrganicCarbonModel/SOCS_0_200cm_1km_Present\").unmask()\n",
    "\n",
    "# mask the diffrence layer\n",
    "SandermannCarbonLoss = SandermannCarbonDiff.multiply(SandermannCarbonDiff.gt(0))\n",
    "\n",
    "# load the present and potential forest cover\n",
    "presentForestCover = compositeImage.select('PresentTreeCover').unmask() # uniform with potential in the  0-1 scale\n",
    "potentialCoverAdjusted = ee.Image(\"users/leonidmoore/ForestBiomass/Bastin_et_al_2019_Potential_Forest_Cover_Adjusted\").unmask().rename('PotentialForestCover')\n",
    "# define the present and potential forest cover masks\n",
    "presentMask = presentForestCover.gt(0)\n",
    "potentialMask = potentialCoverAdjusted.gte(0.1)\n",
    "\n",
    "# calculate the sum of the potential in soil with the consideration of forest cover\n",
    "SandermannCarbonStockLoss = SandermannCarbonLoss.multiply(pixelArea).divide(1000000000).mask(biomeMask).mask(potentialMask).multiply(potentialCoverAdjusted)\n",
    "\n",
    "# add the soil into the PGB as the total potential\n",
    "potentialTotal_Abs = potentialPGB_Abs.add(SandermannCarbonStockLoss)\n",
    "# compose those bands into an image\n",
    "lowerUpperImage = presentAGB_Lower_Abs.rename('preAGB_Lower').addBands(presentAGB_Upper_Abs.rename('preAGB_Upper')).addBands(potentialAGB_Lower_Abs.rename('potAGB_Lower')).addBands(potentialAGB_Upper_Abs.rename('potAGB_Upper')).addBands(presentRoot_Lower_Abs.rename('preRoot_Lower')).addBands(presentRoot_Upper_Abs.rename('preRoot_Upper')).addBands(potentialRoot_Lower_Abs.rename('potRoot_Lower')).addBands(potentialRoot_Upper_Abs.rename('potRoot_Upper')).addBands(presentLitter_Lower_Abs.rename('preLitter_Lower')).addBands(presentLitter_Upper_Abs.rename('preLitter_Upper')).addBands(potentialLitter_Lower_Abs.rename('potLitter_Lower')).addBands(potentialLitter_Upper_Abs.rename('potLitter_Upper')).addBands(potentialTotal_Abs.rename('PotentialTotal'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'state': 'READY',\n",
       " 'description': 'HM1_Upper_Lower_Uncertainty_maps_Export',\n",
       " 'creation_timestamp_ms': 1690806112466,\n",
       " 'update_timestamp_ms': 1690806112466,\n",
       " 'start_timestamp_ms': 0,\n",
       " 'task_type': 'EXPORT_IMAGE',\n",
       " 'id': 'GDYPNT4C4V5FOWMIQU62N35K',\n",
       " 'name': 'projects/earthengine-legacy/operations/GDYPNT4C4V5FOWMIQU62N35K'}"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "exportUpperLower = ee.batch.Export.image.toAsset(image = lowerUpperImage,\n",
    "                                               description = 'HM1_Upper_Lower_Uncertainty_maps_Export',\n",
    "                                               assetId = 'users/leonidmoore/ForestBiomass/UncertaintyFigure/HM1_Lower_Upper_Map',\n",
    "                                               region = unboundedGeo,\n",
    "                                               crs = 'EPSG:4326',\n",
    "                                               crsTransform = [0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                               maxPixels = 1e13)\n",
    "# start the export task\n",
    "exportUpperLower.start()\n",
    "# show the task status\n",
    "exportUpperLower.status()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6 Calculate the Abs for different parts at biome level"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[34mThe biomass partition results in biome: \n",
      "\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>PresentAGB</th>\n",
       "      <th>PotentialAGB</th>\n",
       "      <th>PresentRoot</th>\n",
       "      <th>PotentialRoot</th>\n",
       "      <th>PresentTGB</th>\n",
       "      <th>PotentialTGB</th>\n",
       "      <th>PresentLitter</th>\n",
       "      <th>PotentialLitter</th>\n",
       "      <th>PresentPGB</th>\n",
       "      <th>PotentialPGB</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>136.1</td>\n",
       "      <td>174.5</td>\n",
       "      <td>36.7</td>\n",
       "      <td>46.2</td>\n",
       "      <td>172.8</td>\n",
       "      <td>220.6</td>\n",
       "      <td>38.0</td>\n",
       "      <td>48.5</td>\n",
       "      <td>210.8</td>\n",
       "      <td>269.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>5.2</td>\n",
       "      <td>11.8</td>\n",
       "      <td>1.4</td>\n",
       "      <td>3.1</td>\n",
       "      <td>6.5</td>\n",
       "      <td>14.9</td>\n",
       "      <td>1.4</td>\n",
       "      <td>3.3</td>\n",
       "      <td>8.0</td>\n",
       "      <td>18.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1.7</td>\n",
       "      <td>3.5</td>\n",
       "      <td>0.4</td>\n",
       "      <td>0.9</td>\n",
       "      <td>2.2</td>\n",
       "      <td>4.4</td>\n",
       "      <td>0.5</td>\n",
       "      <td>1.0</td>\n",
       "      <td>2.7</td>\n",
       "      <td>5.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>34.6</td>\n",
       "      <td>56.2</td>\n",
       "      <td>8.9</td>\n",
       "      <td>14.3</td>\n",
       "      <td>43.5</td>\n",
       "      <td>70.5</td>\n",
       "      <td>14.3</td>\n",
       "      <td>23.2</td>\n",
       "      <td>57.8</td>\n",
       "      <td>93.7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>16.4</td>\n",
       "      <td>21.2</td>\n",
       "      <td>4.4</td>\n",
       "      <td>5.7</td>\n",
       "      <td>20.7</td>\n",
       "      <td>26.8</td>\n",
       "      <td>6.8</td>\n",
       "      <td>8.8</td>\n",
       "      <td>27.5</td>\n",
       "      <td>35.7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>36.4</td>\n",
       "      <td>47.5</td>\n",
       "      <td>9.7</td>\n",
       "      <td>12.8</td>\n",
       "      <td>46.1</td>\n",
       "      <td>60.2</td>\n",
       "      <td>36.8</td>\n",
       "      <td>48.1</td>\n",
       "      <td>82.9</td>\n",
       "      <td>108.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>31.5</td>\n",
       "      <td>60.7</td>\n",
       "      <td>9.6</td>\n",
       "      <td>18.4</td>\n",
       "      <td>41.1</td>\n",
       "      <td>79.2</td>\n",
       "      <td>9.0</td>\n",
       "      <td>17.4</td>\n",
       "      <td>50.2</td>\n",
       "      <td>96.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>3.8</td>\n",
       "      <td>17.4</td>\n",
       "      <td>1.1</td>\n",
       "      <td>5.0</td>\n",
       "      <td>4.9</td>\n",
       "      <td>22.4</td>\n",
       "      <td>1.6</td>\n",
       "      <td>7.4</td>\n",
       "      <td>6.5</td>\n",
       "      <td>29.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>1.2</td>\n",
       "      <td>2.5</td>\n",
       "      <td>0.4</td>\n",
       "      <td>0.7</td>\n",
       "      <td>1.6</td>\n",
       "      <td>3.2</td>\n",
       "      <td>0.3</td>\n",
       "      <td>0.7</td>\n",
       "      <td>1.9</td>\n",
       "      <td>3.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>2.7</td>\n",
       "      <td>6.2</td>\n",
       "      <td>0.8</td>\n",
       "      <td>1.7</td>\n",
       "      <td>3.4</td>\n",
       "      <td>7.8</td>\n",
       "      <td>1.1</td>\n",
       "      <td>2.6</td>\n",
       "      <td>4.5</td>\n",
       "      <td>10.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>3.1</td>\n",
       "      <td>6.6</td>\n",
       "      <td>0.9</td>\n",
       "      <td>2.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>8.6</td>\n",
       "      <td>3.2</td>\n",
       "      <td>6.8</td>\n",
       "      <td>7.3</td>\n",
       "      <td>15.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>3.0</td>\n",
       "      <td>7.5</td>\n",
       "      <td>0.9</td>\n",
       "      <td>2.4</td>\n",
       "      <td>3.9</td>\n",
       "      <td>9.9</td>\n",
       "      <td>0.8</td>\n",
       "      <td>2.1</td>\n",
       "      <td>4.7</td>\n",
       "      <td>12.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>2.0</td>\n",
       "      <td>16.7</td>\n",
       "      <td>0.6</td>\n",
       "      <td>4.6</td>\n",
       "      <td>2.6</td>\n",
       "      <td>21.2</td>\n",
       "      <td>0.5</td>\n",
       "      <td>4.5</td>\n",
       "      <td>3.1</td>\n",
       "      <td>25.7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>1.1</td>\n",
       "      <td>2.0</td>\n",
       "      <td>0.2</td>\n",
       "      <td>0.4</td>\n",
       "      <td>1.3</td>\n",
       "      <td>2.4</td>\n",
       "      <td>0.3</td>\n",
       "      <td>0.5</td>\n",
       "      <td>1.6</td>\n",
       "      <td>2.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>sum</th>\n",
       "      <td>278.8</td>\n",
       "      <td>434.3</td>\n",
       "      <td>76.0</td>\n",
       "      <td>118.2</td>\n",
       "      <td>354.6</td>\n",
       "      <td>552.1</td>\n",
       "      <td>114.6</td>\n",
       "      <td>174.9</td>\n",
       "      <td>469.5</td>\n",
       "      <td>727.2</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     PresentAGB  PotentialAGB  PresentRoot  PotentialRoot  PresentTGB  \\\n",
       "0         136.1         174.5         36.7           46.2       172.8   \n",
       "1           5.2          11.8          1.4            3.1         6.5   \n",
       "2           1.7           3.5          0.4            0.9         2.2   \n",
       "3          34.6          56.2          8.9           14.3        43.5   \n",
       "4          16.4          21.2          4.4            5.7        20.7   \n",
       "5          36.4          47.5          9.7           12.8        46.1   \n",
       "6          31.5          60.7          9.6           18.4        41.1   \n",
       "7           3.8          17.4          1.1            5.0         4.9   \n",
       "8           1.2           2.5          0.4            0.7         1.6   \n",
       "9           2.7           6.2          0.8            1.7         3.4   \n",
       "10          3.1           6.6          0.9            2.0         4.0   \n",
       "11          3.0           7.5          0.9            2.4         3.9   \n",
       "12          2.0          16.7          0.6            4.6         2.6   \n",
       "13          1.1           2.0          0.2            0.4         1.3   \n",
       "sum       278.8         434.3         76.0          118.2       354.6   \n",
       "\n",
       "     PotentialTGB  PresentLitter  PotentialLitter  PresentPGB  PotentialPGB  \n",
       "0           220.6           38.0             48.5       210.8         269.2  \n",
       "1            14.9            1.4              3.3         8.0          18.2  \n",
       "2             4.4            0.5              1.0         2.7           5.3  \n",
       "3            70.5           14.3             23.2        57.8          93.7  \n",
       "4            26.8            6.8              8.8        27.5          35.7  \n",
       "5            60.2           36.8             48.1        82.9         108.4  \n",
       "6            79.2            9.0             17.4        50.2          96.6  \n",
       "7            22.4            1.6              7.4         6.5          29.8  \n",
       "8             3.2            0.3              0.7         1.9           3.9  \n",
       "9             7.8            1.1              2.6         4.5          10.4  \n",
       "10            8.6            3.2              6.8         7.3          15.4  \n",
       "11            9.9            0.8              2.1         4.7          12.0  \n",
       "12           21.2            0.5              4.5         3.1          25.7  \n",
       "13            2.4            0.3              0.5         1.6           2.9  \n",
       "sum         552.1          114.6            174.9       469.5         727.2  "
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Stack the absolute biomass layers into an Image.\n",
    "absImage = presentAGB_Abs.rename('PresentAGB').addBands(potentialAGB_Abs.rename('PotentialAGB')).addBands(presentRoot_Abs.rename('PresentRoot')).addBands(potentialRoot_Abs.rename('PotentialRoot')).addBands(presentTGB_Abs.rename('PresentTGB')).addBands(potentialTGB_Abs.rename('PotentialTGB')).addBands(presentLitter_Abs.rename('PresentLitter')).addBands(potentialLitter_Abs.rename('PotentialLitter')).addBands(presentPGB_Abs.rename('PresentPGB')).addBands(potentialPGB_Abs.rename('PotentialPGB'))\n",
    "\n",
    "# define the function to do the biome level statistics which could be applied by map      \n",
    "def biomeLevelStat(biome):\n",
    "    perBiomeMask = biomeLayer.eq(ee.Number(biome))\n",
    "    masked_img = absImage.mask(perBiomeMask)\n",
    "    output = masked_img.reduceRegion(reducer= ee.Reducer.sum(),\n",
    "                                     geometry= unboundedGeo,\n",
    "                                     crs='EPSG:4326',\n",
    "                                     crsTransform=[0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                     maxPixels= 1e13)\n",
    "    return output#.getInfo().get('Present')\n",
    "\n",
    "\n",
    "biomeList = ee.List([1,2,3,4,5,6,7,8,9,10,11,12,13,14])\n",
    "statisticTable = biomeList.map(biomeLevelStat).getInfo()\n",
    "# transform into data frame\n",
    "outputTable = pd.DataFrame(statisticTable,columns =['PresentAGB','PotentialAGB','PresentRoot','PotentialRoot','PresentTGB','PotentialTGB','PresentLitter','PotentialLitter','PresentPGB','PotentialPGB']).round(1)\n",
    "outputTable.loc['sum'] = outputTable.sum() \n",
    "outputTable.to_csv('Data/BiomeLevelStatistics/StatisticsForModels/HM1_Abs_for_diff_parts_at_Biome_Level.csv',header=True,mode='w+')\n",
    "print(colored('The biomass partition results in biome: \\n', 'blue', attrs=['bold']))\n",
    "outputTable.head(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If you got the error 'EEException: Too many concurrent aggregations.', please re-run this chunck of code again."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7 Calculate the Abs for different parts at biome level"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[34mThe biomass partition results in biome: \n",
      "\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>preAGB_Lower</th>\n",
       "      <th>preAGB_Upper</th>\n",
       "      <th>potAGB_Lower</th>\n",
       "      <th>potAGB_Upper</th>\n",
       "      <th>preRoot_Lower</th>\n",
       "      <th>preRoot_Upper</th>\n",
       "      <th>potRoot_Lower</th>\n",
       "      <th>potRoot_Upper</th>\n",
       "      <th>preLitter_Lower</th>\n",
       "      <th>preLitter_Upper</th>\n",
       "      <th>potLitter_Lower</th>\n",
       "      <th>potLitter_Upper</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>61.4</td>\n",
       "      <td>211.0</td>\n",
       "      <td>153.3</td>\n",
       "      <td>199.5</td>\n",
       "      <td>12.9</td>\n",
       "      <td>70.1</td>\n",
       "      <td>32.2</td>\n",
       "      <td>64.7</td>\n",
       "      <td>11.2</td>\n",
       "      <td>84.3</td>\n",
       "      <td>27.8</td>\n",
       "      <td>79.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2.2</td>\n",
       "      <td>8.2</td>\n",
       "      <td>10.0</td>\n",
       "      <td>13.7</td>\n",
       "      <td>0.5</td>\n",
       "      <td>2.6</td>\n",
       "      <td>2.1</td>\n",
       "      <td>4.1</td>\n",
       "      <td>0.4</td>\n",
       "      <td>3.2</td>\n",
       "      <td>1.8</td>\n",
       "      <td>5.4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>0.8</td>\n",
       "      <td>2.7</td>\n",
       "      <td>3.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>0.2</td>\n",
       "      <td>0.8</td>\n",
       "      <td>0.7</td>\n",
       "      <td>1.2</td>\n",
       "      <td>0.1</td>\n",
       "      <td>1.1</td>\n",
       "      <td>0.5</td>\n",
       "      <td>1.5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>14.8</td>\n",
       "      <td>54.9</td>\n",
       "      <td>46.7</td>\n",
       "      <td>63.2</td>\n",
       "      <td>3.4</td>\n",
       "      <td>16.0</td>\n",
       "      <td>10.6</td>\n",
       "      <td>18.3</td>\n",
       "      <td>5.5</td>\n",
       "      <td>26.2</td>\n",
       "      <td>17.2</td>\n",
       "      <td>30.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>7.8</td>\n",
       "      <td>25.0</td>\n",
       "      <td>16.8</td>\n",
       "      <td>22.9</td>\n",
       "      <td>1.8</td>\n",
       "      <td>7.6</td>\n",
       "      <td>3.9</td>\n",
       "      <td>7.0</td>\n",
       "      <td>2.9</td>\n",
       "      <td>12.1</td>\n",
       "      <td>6.2</td>\n",
       "      <td>11.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>16.7</td>\n",
       "      <td>56.4</td>\n",
       "      <td>38.4</td>\n",
       "      <td>50.8</td>\n",
       "      <td>4.1</td>\n",
       "      <td>16.7</td>\n",
       "      <td>9.5</td>\n",
       "      <td>15.3</td>\n",
       "      <td>14.1</td>\n",
       "      <td>68.6</td>\n",
       "      <td>32.5</td>\n",
       "      <td>62.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>12.9</td>\n",
       "      <td>51.1</td>\n",
       "      <td>49.4</td>\n",
       "      <td>70.9</td>\n",
       "      <td>3.3</td>\n",
       "      <td>18.0</td>\n",
       "      <td>12.7</td>\n",
       "      <td>25.0</td>\n",
       "      <td>2.4</td>\n",
       "      <td>20.7</td>\n",
       "      <td>9.3</td>\n",
       "      <td>28.8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>1.5</td>\n",
       "      <td>6.7</td>\n",
       "      <td>13.7</td>\n",
       "      <td>20.9</td>\n",
       "      <td>0.4</td>\n",
       "      <td>2.2</td>\n",
       "      <td>3.5</td>\n",
       "      <td>7.1</td>\n",
       "      <td>0.6</td>\n",
       "      <td>3.3</td>\n",
       "      <td>5.2</td>\n",
       "      <td>10.3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>0.5</td>\n",
       "      <td>2.0</td>\n",
       "      <td>2.0</td>\n",
       "      <td>2.9</td>\n",
       "      <td>0.1</td>\n",
       "      <td>0.7</td>\n",
       "      <td>0.5</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.1</td>\n",
       "      <td>0.8</td>\n",
       "      <td>0.4</td>\n",
       "      <td>1.2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>1.1</td>\n",
       "      <td>4.4</td>\n",
       "      <td>4.8</td>\n",
       "      <td>7.4</td>\n",
       "      <td>0.3</td>\n",
       "      <td>1.4</td>\n",
       "      <td>1.1</td>\n",
       "      <td>2.3</td>\n",
       "      <td>0.4</td>\n",
       "      <td>2.1</td>\n",
       "      <td>1.8</td>\n",
       "      <td>3.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>1.3</td>\n",
       "      <td>5.6</td>\n",
       "      <td>4.9</td>\n",
       "      <td>7.8</td>\n",
       "      <td>0.3</td>\n",
       "      <td>2.0</td>\n",
       "      <td>1.3</td>\n",
       "      <td>2.9</td>\n",
       "      <td>1.1</td>\n",
       "      <td>7.1</td>\n",
       "      <td>4.2</td>\n",
       "      <td>10.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>1.3</td>\n",
       "      <td>4.8</td>\n",
       "      <td>5.9</td>\n",
       "      <td>8.9</td>\n",
       "      <td>0.3</td>\n",
       "      <td>2.0</td>\n",
       "      <td>1.6</td>\n",
       "      <td>3.7</td>\n",
       "      <td>0.0</td>\n",
       "      <td>2.7</td>\n",
       "      <td>0.2</td>\n",
       "      <td>5.1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>0.8</td>\n",
       "      <td>3.4</td>\n",
       "      <td>12.2</td>\n",
       "      <td>21.8</td>\n",
       "      <td>0.2</td>\n",
       "      <td>1.3</td>\n",
       "      <td>2.9</td>\n",
       "      <td>7.3</td>\n",
       "      <td>0.0</td>\n",
       "      <td>1.9</td>\n",
       "      <td>0.3</td>\n",
       "      <td>11.6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>0.5</td>\n",
       "      <td>1.7</td>\n",
       "      <td>1.6</td>\n",
       "      <td>2.2</td>\n",
       "      <td>0.1</td>\n",
       "      <td>0.5</td>\n",
       "      <td>0.3</td>\n",
       "      <td>0.7</td>\n",
       "      <td>0.1</td>\n",
       "      <td>0.6</td>\n",
       "      <td>0.3</td>\n",
       "      <td>0.9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>sum</th>\n",
       "      <td>123.6</td>\n",
       "      <td>437.9</td>\n",
       "      <td>362.7</td>\n",
       "      <td>496.9</td>\n",
       "      <td>27.9</td>\n",
       "      <td>141.9</td>\n",
       "      <td>82.9</td>\n",
       "      <td>160.6</td>\n",
       "      <td>38.9</td>\n",
       "      <td>234.7</td>\n",
       "      <td>107.7</td>\n",
       "      <td>260.9</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "     preAGB_Lower  preAGB_Upper  potAGB_Lower  potAGB_Upper  preRoot_Lower  \\\n",
       "0            61.4         211.0         153.3         199.5           12.9   \n",
       "1             2.2           8.2          10.0          13.7            0.5   \n",
       "2             0.8           2.7           3.0           4.0            0.2   \n",
       "3            14.8          54.9          46.7          63.2            3.4   \n",
       "4             7.8          25.0          16.8          22.9            1.8   \n",
       "5            16.7          56.4          38.4          50.8            4.1   \n",
       "6            12.9          51.1          49.4          70.9            3.3   \n",
       "7             1.5           6.7          13.7          20.9            0.4   \n",
       "8             0.5           2.0           2.0           2.9            0.1   \n",
       "9             1.1           4.4           4.8           7.4            0.3   \n",
       "10            1.3           5.6           4.9           7.8            0.3   \n",
       "11            1.3           4.8           5.9           8.9            0.3   \n",
       "12            0.8           3.4          12.2          21.8            0.2   \n",
       "13            0.5           1.7           1.6           2.2            0.1   \n",
       "sum         123.6         437.9         362.7         496.9           27.9   \n",
       "\n",
       "     preRoot_Upper  potRoot_Lower  potRoot_Upper  preLitter_Lower  \\\n",
       "0             70.1           32.2           64.7             11.2   \n",
       "1              2.6            2.1            4.1              0.4   \n",
       "2              0.8            0.7            1.2              0.1   \n",
       "3             16.0           10.6           18.3              5.5   \n",
       "4              7.6            3.9            7.0              2.9   \n",
       "5             16.7            9.5           15.3             14.1   \n",
       "6             18.0           12.7           25.0              2.4   \n",
       "7              2.2            3.5            7.1              0.6   \n",
       "8              0.7            0.5            1.0              0.1   \n",
       "9              1.4            1.1            2.3              0.4   \n",
       "10             2.0            1.3            2.9              1.1   \n",
       "11             2.0            1.6            3.7              0.0   \n",
       "12             1.3            2.9            7.3              0.0   \n",
       "13             0.5            0.3            0.7              0.1   \n",
       "sum          141.9           82.9          160.6             38.9   \n",
       "\n",
       "     preLitter_Upper  potLitter_Lower  potLitter_Upper  \n",
       "0               84.3             27.8             79.3  \n",
       "1                3.2              1.8              5.4  \n",
       "2                1.1              0.5              1.5  \n",
       "3               26.2             17.2             30.1  \n",
       "4               12.1              6.2             11.1  \n",
       "5               68.6             32.5             62.0  \n",
       "6               20.7              9.3             28.8  \n",
       "7                3.3              5.2             10.3  \n",
       "8                0.8              0.4              1.2  \n",
       "9                2.1              1.8              3.6  \n",
       "10               7.1              4.2             10.0  \n",
       "11               2.7              0.2              5.1  \n",
       "12               1.9              0.3             11.6  \n",
       "13               0.6              0.3              0.9  \n",
       "sum            234.7            107.7            260.9  "
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Stack the absolute biomass layers into an Image.\n",
    "absPotentialImage = presentAGB_Lower_Abs.rename('preAGB_Lower').addBands(presentAGB_Upper_Abs.rename('preAGB_Upper')).addBands(potentialAGB_Lower_Abs.rename('potAGB_Lower')).addBands(potentialAGB_Upper_Abs.rename('potAGB_Upper')).addBands(presentRoot_Lower_Abs.rename('preRoot_Lower')).addBands(presentRoot_Upper_Abs.rename('preRoot_Upper')).addBands(potentialRoot_Lower_Abs.rename('potRoot_Lower')).addBands(potentialRoot_Upper_Abs.rename('potRoot_Upper')).addBands(presentLitter_Lower_Abs.rename('preLitter_Lower')).addBands(presentLitter_Upper_Abs.rename('preLitter_Upper')).addBands(potentialLitter_Lower_Abs.rename('potLitter_Lower')).addBands(potentialLitter_Upper_Abs.rename('potLitter_Upper'))\n",
    "# define the function to do the biome level statistics which could be applied by map      \n",
    "def biomeLevelStat(biome):\n",
    "    perBiomeMask = biomeLayer.eq(ee.Number(biome))\n",
    "    masked_img = absPotentialImage.mask(perBiomeMask)\n",
    "    output = masked_img.reduceRegion(reducer= ee.Reducer.sum(),\n",
    "                                     geometry= unboundedGeo,\n",
    "                                     crs='EPSG:4326',\n",
    "                                     crsTransform=[0.008333333333333333,0,-180,0,-0.008333333333333333,90],\n",
    "                                     maxPixels= 1e13)\n",
    "    return output#.getInfo().get('Present')\n",
    "\n",
    "\n",
    "biomeList = ee.List([1,2,3,4,5,6,7,8,9,10,11,12,13,14])\n",
    "statisticTable = biomeList.map(biomeLevelStat).getInfo()\n",
    "# transform into data frame\n",
    "outputTable = pd.DataFrame(statisticTable,columns =['preAGB_Lower','preAGB_Upper','potAGB_Lower','potAGB_Upper','preRoot_Lower','preRoot_Upper','potRoot_Lower','potRoot_Upper','preLitter_Lower','preLitter_Upper','potLitter_Lower','potLitter_Upper']).round(1)\n",
    "outputTable.loc['sum'] = outputTable.sum() \n",
    "outputTable.to_csv('Data/BiomeLevelStatistics/StatisticsForModels/HM1_Uncertainty_for_diff_parts_at_Biome_Level.csv',header=True,mode='w+')\n",
    "print(colored('The biomass partition results in biome: \\n', 'blue', attrs=['bold']))\n",
    "outputTable.head(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If you got the error 'EEException: Too many concurrent aggregations.', please re-run this chunck of code again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
